import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import styles from "../style/buynow.module.css";
import leftItem from "../img/left.png";
import { address } from "../api/address"; //收货地址接口
import { shopping_play } from "../api/shopping";//购物车结算
interface PurchaseData {
  id: number;
  goods_id: number;
  money: number;
  name: string;
  img: string;
  num: number;
  title: string;
}
interface Address {
  id: number;
  name: string;
  tel: string;
  default: number;
  address: string;
  title: string;
}
const BuynowPage = () => {
  const navigate = useNavigate();
  const [quantity, setQuantity] = useState(1);
  const [showHint, setShowHint] = useState(false);
  const [productData, setProductData] = useState<PurchaseData[] | null>(null);
  const [shopID, setShopID] = useState(1);
  const [allMoney, setAllMoney] = useState(0);
  const user = JSON.parse(localStorage.getItem("user") || "null"); //用户数据
  console.log(user.data.token, "请求头token");
  console.log(user.data.id, "请求id");
  interface NormItem {
    name: string;
    value: string;
  }
  const [normData, setnormData] = useState<NormItem[]>([]);
  console.log(JSON.stringify(normData));

  // 从本地存储读取商品数据
  useEffect(() => {
    const storedData = sessionStorage.getItem("renderData");
    console.log(storedData, "本地存储中的商品数据");

    if (storedData) {
      try {
        const data: PurchaseData[] = JSON.parse(storedData);
        console.log("商品数据解析成功:", data);
        const total = data.reduce(
          (sum, product) => sum + product.num * product.money,
          0
        );
        setAllMoney(total);
        setProductData(data);
      } catch (error) {
        console.error("解析商品数据失败:", error);
        navigate("/");
      }
    } else {
      navigate("/");
    }
  }, [navigate]);

  const handleQuantity = (action: "add" | "subtract", id: number) => {
    setProductData((prevData) => {
      if (!prevData) return prevData; // 如果 prevData 为空，直接返回

      // 找到需要更新的商品
      const updatedData = prevData.map((product) => {
        if (product.id === id) {
          let newQuantity = product.num;

          // 根据 action 更新数量
          if (action === "add") {
            newQuantity += 1; // 增加数量
          } else if (action === "subtract") {
            newQuantity = Math.max(1, product.num - 1); // 减少数量，至少为 1
          }

          return { ...product, num: newQuantity }; // 更新数量
        }
        return product;
      });

      // 计算总价
      const total = updatedData.reduce(
        (sum, product) => sum + product.num * product.money,
        0
      );
      setAllMoney(total); // 更新总价
      setProductData(updatedData);
      return updatedData;
    });
  };

  const updateQuantity = (id: number, newQuantity: number) => {
    // 确保数量至少为 1
    newQuantity = Math.max(1, newQuantity);

    // 更新 productData 中对应商品的数量
    setProductData((prevData) => {
      if (!prevData) return prevData; // 如果 prevData 为空，直接返回

      // 找到需要更新的商品
      const updatedData = prevData.map((product) => {
        if (product.id === id) {
          return { ...product, num: newQuantity }; // 更新数量
        }
        return product;
      });

      // 计算总价
      const total = updatedData.reduce(
        (sum, product) => sum + product.num * product.money,
        0
      );
      setAllMoney(total); // 更新总价
      setProductData(updatedData);

      return updatedData;
    });
  };
  // 地址信息渲染
  useEffect(() => {
    fetchAddress();
  }, []);
  const [addressList, setAddressList] = useState<Address[]>([]);
  const [addID, setAddID] = useState<number | null>(null);
  const fetchAddress = async () => {
    try {
      const userid = user.data.id;
      const response = await address({
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        data: { uid: userid }, 
      });
      const res = response.data; // 直接访问 response.data
      console.log(res, "数据");
      setAddressList(res?.data || []);
      setAddID(res?.data[0]?.id);
    } catch (error) {
      console.error("Error fetching addresses:", error);
    }
  };
  // =====================================立即购买接口================================================
  const handleBuy = () => {
    if (!productData) {
      console.error("productData 为 null,无法处理");
      return; // 提前返回
    }

    console.log(productData, "立即购买接口");

    const shopping_ids = productData.map((product) => ({
      id: product.id, // 商品 ID
      goods_id: product.goods_id, // 商品 goods_id
      num: product.num, // 商品数量
      money: product.money, // 商品价格
      title: product.name, // 商品名称
    }));

    // 转换为单行字符串
    const shopping_ids_string = JSON.stringify(shopping_ids);

    console.log(shopping_ids_string);
    console.log(shopping_ids, "构造后的 shopping_ids");
    shopping_play({
      shopping_ids: shopping_ids_string, // 使用转换后的字符串
      user_id: user.data.id,
      address_id: addID,
    })
      .then((response) => {
        console.log(response, "立即购买");
      })
      .catch((error) => {
        console.error("请求失败:", error);
      });
    if (!productData || quantity < 1) {
      setShowHint(true);
      setTimeout(() => setShowHint(false), 2000);
      return;
    }
    navigate("/successful");
  };

  if (!productData) {
    return <div className={styles.loading}>加载中...</div>;
  }
  const goBack = () => navigate(-1);
  return (
    <div className={styles.container}>
      {/* 顶部导航 */}
      <div className={styles.top}>
        <div>
          <img onClick={goBack} src={leftItem} alt="" />
          <b>订单购买</b>
        </div>
      </div>

      {/* 地址选择 */}
      <div
        className={styles.addressSection}
        onClick={() => navigate("/address")}
      >
        <div className={styles.addressContent}>
          <span className={styles.addressHint}>
            <span className={styles.addressText}>
              {addressList.length > 0
                ? addressList[0].name + " " + addressList[0].address
                : "请选择收货地址"}
            </span>
          </span>
        </div>
        <img
          src={require("../img/right.png")}
          alt="箭头"
          className={styles.arrowIcon}
        />
      </div>

      {/* 商品信息 */}
      <div className={styles.productList}>
        {productData.map((product) => (
          <div key={product.id} className={styles.productCard}>
            <img src={product.img} alt="商品图片" />
            <div className={styles.productInfo}>
              <h3>{product.name}</h3>
              <p>{product.name}</p>
              <div className={styles.priceRow}>
                <span className={styles.price}>
                  ￥{product.money.toFixed(2)}
                </span>
                <div className={styles.quantityControl}>
                  <button
                    className={styles.quantityControlButton}
                    onClick={() => handleQuantity("subtract", product.id)}
                    aria-label="减少数量"
                  >
                    <img src={require("../img/jian.png")} alt="减少" />
                  </button>
                  <input
                    type="number"
                    value={product.num}
                    onChange={(e) => {
                      const newQuantity = Math.max(1, +e.target.value);
                      updateQuantity(product.id, newQuantity);
                    }}
                    aria-label="购买数量"
                    min="1"
                  />
                  <button
                    className={styles.quantityControlButton}
                    onClick={() => handleQuantity("add", product.id)}
                    aria-label="增加数量"
                  >
                    <img src={require("../img/add.png")} alt="增加" />
                  </button>
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* 价格明细 */}
      <div className={styles.priceDetails}>
        <div className={styles.priceRow}>
          <span>商品金额:</span>
          {allMoney}
        </div>
        <div className={styles.priceRow}>
          <span>运费:</span>
          <span>￥0</span>
        </div>
        <div className={styles.divider} />
        <div className={styles.totalPrice}>
          <span>总价:</span>
          <span className={styles.amount}>{allMoney}</span>
        </div>
      </div>

      {/* 底部操作栏 */}
      <div className={styles.footer}>
        <div className={styles.total}>
          总价:{allMoney}
        </div>
        <button className={styles.buyButton} onClick={handleBuy}>
          立即购买
        </button>
      </div>

      {/* 提示信息 */}
      {showHint && (
        <div className={styles.hintBox}>
          <div className={styles.hintMessage}>输入框不得为空！</div>
        </div>
      )}
    </div>
  );
};

export default BuynowPage;
